package com.yonyou.pmclouds.repeatwork.process;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonMaintain;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonQuery;
import com.yonyou.pmclouds.repeatwork.entity.RepeatWorkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RepeatWorkCopyPersonUpdateBatchProcessor implements SingleProcessor<RepeatWorkVO> {
    @Autowired
    private ICopyPersonMaintain copyPersonMaintain;

    @Autowired
    private ICopyPersonQuery iCopyPersonQuery;

    @Override
    public void process(RepeatWorkVO vo, RepeatWorkVO orig) throws BusinessException {
        List<CopyPersonVO> currentVOs = vo.getCopyPersons();

        List<String> ids = new ArrayList<>();
        ids.add(vo.getPkRepeatwork());
        List<CopyPersonVO> copyPersonsDB = iCopyPersonQuery.queryByPkBills(ids);

        Map<String, CopyPersonVO> current = new HashMap<>();
        Map<String, CopyPersonVO> db = new HashMap<>();

        for (CopyPersonVO copyPersonVO : currentVOs) {
            current.put(copyPersonVO.getCopyPerson(), copyPersonVO);
        }

        for (CopyPersonVO copyPersonVO : copyPersonsDB) {
            db.put(copyPersonVO.getCopyPerson(), copyPersonVO);
        }

        List<CopyPersonVO> insertVOS = new ArrayList<>();
        List<CopyPersonVO> deleteVOS = new ArrayList<>();

        for (CopyPersonVO copyPersonVO : copyPersonsDB) {
            if (null == current.get(copyPersonVO.getCopyPerson())) {
                copyPersonVO.setPkBill(vo.getPkRepeatwork());
                deleteVOS.add(copyPersonVO);
            }
        }

        for (CopyPersonVO copyPersonVO : currentVOs) {
            if (null == db.get(copyPersonVO.getCopyPerson())) {
                copyPersonVO.setPkBill(vo.getPkRepeatwork());
                insertVOS.add(copyPersonVO);
            }
        }

        if (null != insertVOS && insertVOS.size() > 0) {
            copyPersonMaintain.insertBatch(insertVOS);
        }

        if (null != deleteVOS && deleteVOS.size() > 0) {
            copyPersonMaintain.deleteBatchForCopypersion(deleteVOS, vo.getPkRepeatwork());
        }
    }
}
